/**
 * @file 用于缩放屏幕
 * @author zhangyuhan2016 <hi_zhangyuhan@163.com>
 */

/**
 *  @class
 *  @classdesc 缩放屏幕
 *  @desc 用于缩放屏幕保持比例
 */

class ChangeView {
  /**
   * 构造参数
   * @param x 设计图x值
   * @param y 设计图y值
   * @param selector 缩放的Dom
   */
  constructor (x = 375, y = 667, selector = '#app') {
    this.x = x
    this.y = y
    this.box = 'body'
    this.selector = selector
    let b = document.createElement('div')
    b.id = 'app-h'
    b.css = this.css
    b.css({
      width: '100vw',
      height: '100vh',
      display: 'block',
      top: '0',
      left: '0',
      position: 'absolute',
      'z-index': '-999'
    })
    document.querySelector('body').append(b)
  }

  /**
   * 模拟链式调用
   * @param s 选择器
   * @returns {ElementTagNameMap[keyof ElementTagNameMap]}
   */
  qSelector (s) {
    let t = document.querySelector(s)
    t.css = this.css
    return t
  }

  /**
   * 模拟jQ的css方法
   * @param obj Styles对象
   * @returns {ChangeView}
   */
  css (obj) {
    for (let i in obj) {
      this.style[i] = obj[i]
    }
    return this
  }

  /**
   * 获取可视区域x,y进行缩放
   */
  start () {
    let w = window.screen.width
    let h = window.screen.height
    let tempH = document.querySelector('#app-h').clientHeight
    h = tempH
    let scale = w / this.x
    if (scale > 1) {
      console.warn('不推荐放大')
    }
    this.qSelector(this.box).css({
      width: w + 'px',
      height: h + 'px',
      overflow: 'hidden',
      'overflow-y': 'auto'
    })

    this.qSelector(this.selector).css({
      'transform-origin': '0 0 0',
      width: this.x + 'px',
      height: h / scale + 'px',
      'overflow-y': 'auto',
      'transform': `translate3d(0,0,0) scale(${scale})`
    })
  }
}

export default ChangeView
